import express from 'express';
import aiService from '../services/aiService.js';
import authenticateToken from '../middleware/auth.js';

const router = express.Router();

/**
 * @swagger
 * tags:
 *   name: AI服务
 *   description: AI聊天和故事生成相关接口
 */

/**
 * @swagger
 * components:
 *   schemas:
 *     ChatRequest:
 *       type: object
 *       required:
 *         - message
 *       properties:
 *         message:
 *           type: string
 *           description: 用户发送的消息内容
 *         fileUrl:
 *           type: string
 *           description: 文件URL（如图片或音频）
 *         fileType:
 *           type: string
 *           enum: [image, audio]
 *           description: 文件类型，可以是image或audio
 *       example:
 *         message: 你好，AI助手
 *         fileUrl: https://example.com/image.jpg
 *         fileType: image
 *     
 *     ChatResponse:
 *       type: object
 *       properties:
 *         success:
 *           type: boolean
 *           description: 请求是否成功
 *         data:
 *           type: object
 *           properties:
 *             message:
 *               type: string
 *               description: AI回复的消息内容
 *         message:
 *           type: string
 *           description: 错误信息（如果有）
 *       example:
 *         success: true
 *         data:
 *           message: 你好！我是AI助手，有什么可以帮到你？
 *     
 *     ChatHistoryItem:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 消息ID
 *         role:
 *           type: string
 *           enum: [user, ai]
 *           description: 消息发送者角色
 *         content:
 *           type: string
 *           description: 消息内容
 *         file_url:
 *           type: string
 *           description: 文件URL（如果有）
 *         file_type:
 *           type: string
 *           description: 文件类型（如果有）
 *         created_at:
 *           type: string
 *           format: date-time
 *           description: 消息创建时间
 *     
 *     StoryRequest:
 *       type: object
 *       required:
 *         - prompt
 *       properties:
 *         prompt:
 *           type: string
 *           description: 故事生成的提示内容
 *       example:
 *         prompt: 请生成一个关于小狗历险记的短故事
 *     
 *     StoryResponse:
 *       type: object
 *       properties:
 *         success:
 *           type: boolean
 *           description: 请求是否成功
 *         story:
 *           type: string
 *           description: 生成的故事内容
 *         error:
 *           type: string
 *           description: 错误信息（如果有）
 */

/**
 * @swagger
 * /api/ai/chat:
 *   post:
 *     summary: 发送消息给AI助手
 *     tags: [AI服务]
 *     security:
 *       - BearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/ChatRequest'
 *     responses:
 *       200:
 *         description: 成功获取AI回复
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ChatResponse'
 *       401:
 *         description: 未授权
 *       500:
 *         description: 服务器错误
 */
router.post('/chat', authenticateToken, async (req, res) => {
  try {
    const { message, fileUrl, fileType } = req.body;
    const userId = req.user?.id || req.ip;
    
    // 打印接收到的消息和文件信息
    console.log('Chat request received:', { 
      userId, 
      message, 
      hasFile: !!fileUrl,
      fileType 
    });
    
    // 调用AI服务处理带文件的消息
    const response = await aiService.chat(message, userId, fileUrl, fileType);
    
    res.json(response);
  } catch (error) {
    console.error('Error in chat API:', error);
    res.status(500).json({
      success: false,
      message: error.message || '服务器错误'
    });
  }
});

/**
 * @swagger
 * /api/ai/history:
 *   get:
 *     summary: 获取用户聊天历史
 *     tags: [AI服务]
 *     security:
 *       - BearerAuth: []
 *     responses:
 *       200:
 *         description: 成功获取聊天历史
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 data:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/ChatHistoryItem'
 *       401:
 *         description: 未授权
 *       500:
 *         description: 服务器错误
 */
router.get('/history', authenticateToken, async (req, res) => {
  try {
    const userId = req.user?.id || req.ip;
    const history = await aiService.getChatHistory(userId);
    
    res.json({
      success: true,
      data: history
    });
  } catch (error) {
    console.error('Error getting chat history:', error);
    res.status(500).json({
      success: false,
      message: error.message || '服务器错误'
    });
  }
});

/**
 * @swagger
 * /api/ai/generate-story:
 *   post:
 *     summary: 生成故事
 *     tags: [AI服务]
 *     security:
 *       - BearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/StoryRequest'
 *     responses:
 *       200:
 *         description: 成功生成故事
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/StoryResponse'
 *       401:
 *         description: 未授权
 *       500:
 *         description: 服务器错误
 */
router.post('/generate-story', authenticateToken, async (req, res) => {
  try {
    const { prompt } = req.body;
    const userId = req.user?.id || req.ip;
    
    const result = await aiService.constructor.generateStory(prompt, userId);
    res.json(result);
  } catch (error) {
    console.error('Error generating story:', error);
    res.status(500).json({
      success: false,
      error: error.message || '生成故事失败'
    });
  }
});

export default router; 